package br.com.xml;

import java.util.ArrayList;

import com.hp.hpl.jena.graph.NodeFactory;
import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.ResultSetFormatter;

public class Recuperar {
	private String uri, endpoint;
		
	public Recuperar() {
		super();
	}

	public Recuperar(String uri, String endpoint) {
		super();
		this.uri = uri;
		this.endpoint = endpoint;
	}
	
	public String getUri() {
		return uri;
	}

	public void setUri(String uri) {
		this.uri = uri;
	}

	public String getEndpoint() {
		return endpoint;
	}

	public void setEndpoint(String endpoint) {
		this.endpoint = endpoint;
	}

	public Triple[] exec() {
		ArrayList<Triple> triples = new ArrayList<Triple>();
		
		//SPARQL query
		String sparqlQueryString = 					
				"SELECT DISTINCT ?a ?b WHERE { ?a ?b <"+ uri +"> } LIMIT 100";
		
		//connect and execute
		Query query = QueryFactory.create(sparqlQueryString);
		QueryExecution qexec = QueryExecutionFactory.sparqlService(endpoint, query);

		//print result
		ResultSet results = qexec.execSelect();
		for(QuerySolution qs : ResultSetFormatter.toList(results)) {
			Triple t = new Triple(qs.get("a").asNode(), qs.get("b").asNode(), NodeFactory.createURI(uri));
			
			triples.add(t);
		}

		//closing connection
		qexec.close() ;
		
		//preparing return
		Triple[] tArray = new Triple[triples.size()];
		tArray = triples.toArray(tArray);
				
		//return
		return tArray;
	}
}
